/**
 * 基础组件类
 * 提供组件生命周期管理、事件系统、状态管理等基础功能
 */
class BaseComponent {
    constructor(options = {}) {
        this.id = options.id || this.generateId();
        this.element = options.element || null;
        this.container = options.container || null;
        this.props = options.props || {};
        this.state = {};
        this.events = {};
        this.children = [];
        this.parent = null;
        this.isMounted = false;
        this.isDestroyed = false;

        // 初始化配置
        this.config = {
            debug: false,
            autoRender: true,
            ...options.config
        };

        // 组件样式类
        this.className = options.className || '';

        // 如果提供了容器元素，直接挂载
        if (this.container) {
            this.mount(this.container);
        }
    }

    /**
     * 生成唯一ID
     */
    generateId() {
        return `component_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    }

    /**
     * 挂载组件到容器
     */
    mount(container) {
        if (this.isMounted) {
            console.warn(`Component ${this.id} is already mounted`);
            return this;
        }

        this.container = typeof container === 'string'
            ? document.querySelector(container)
            : container;

        if (!this.container) {
            throw new Error(`Container not found for component ${this.id}`);
        }

        // 渲染组件
        if (this.config.autoRender) {
            this.render();
        }

        // 绑定事件
        this.bindEvents();

        this.isMounted = true;
        this.emit('mounted');

        if (this.config.debug) {
            console.log(`Component ${this.id} mounted`);
        }

        return this;
    }

    /**
     * 卸载组件
     */
    unmount() {
        if (!this.isMounted || this.isDestroyed) {
            return this;
        }

        // 解绑事件
        this.unbindEvents();

        // 销毁子组件
        this.children.forEach(child => {
            if (child.unmount) {
                child.unmount();
            }
        });

        // 清空容器
        if (this.container && this.element) {
            this.container.removeChild(this.element);
        }

        this.isMounted = false;
        this.isDestroyed = true;
        this.emit('unmounted');

        if (this.config.debug) {
            console.log(`Component ${this.id} unmounted`);
        }

        return this;
    }

    /**
     * 渲染组件 - 子类必须实现
     */
    render() {
        throw new Error('render method must be implemented in subclass');
    }

    /**
     * 更新组件
     */
    update() {
        if (!this.isMounted || this.isDestroyed) {
            return this;
        }

        this.emit('beforeUpdate');

        // 重新渲染
        this.render();

        // 重新绑定事件
        this.unbindEvents();
        this.bindEvents();

        this.emit('updated');
        return this;
    }

    /**
     * 绑定事件 - 子类可以重写
     */
    bindEvents() {
        // 子类实现具体事件绑定
    }

    /**
     * 解绑事件 - 子类可以重写
     */
    unbindEvents() {
        // 解绑所有事件
        Object.keys(this.events).forEach(event => {
            this.events[event].forEach(callback => {
                if (this.element) {
                    this.element.removeEventListener(event, callback);
                }
            });
        });
        this.events = {};
    }

    /**
     * 设置状态
     */
    setState(newState) {
        const oldState = { ...this.state };
        this.state = { ...this.state, ...newState };

        // 触发状态更新
        this.emit('stateChanged', { oldState, newState: this.state });

        // 自动更新组件
        if (this.config.autoRender) {
            this.update();
        }

        return this;
    }

    /**
     * 更新属性
     */
    setProps(newProps) {
        const oldProps = { ...this.props };
        this.props = { ...this.props, ...newProps };

        // 触发属性更新
        this.emit('propsChanged', { oldProps, newProps: this.props });

        // 自动更新组件
        if (this.config.autoRender) {
            this.update();
        }

        return this;
    }

    /**
     * 添加子组件
     */
    addChild(child) {
        if (!(child instanceof BaseComponent)) {
            throw new Error('Child must be an instance of BaseComponent');
        }

        child.parent = this;
        this.children.push(child);

        // 如果当前组件已挂载，自动挂载子组件
        if (this.isMounted && this.element) {
            // 找到合适的容器挂载子组件
            const childContainer = this.element.querySelector(`[data-child-container="${child.id}"]`) || this.element;
            child.mount(childContainer);
        }

        return this;
    }

    /**
     * 移除子组件
     */
    removeChild(child) {
        const index = this.children.indexOf(child);
        if (index > -1) {
            this.children.splice(index, 1);
            if (child.unmount) {
                child.unmount();
            }
        }
        return this;
    }

    /**
     * 事件监听
     */
    on(event, callback) {
        if (!this.events[event]) {
            this.events[event] = [];
        }
        this.events[event].push(callback);
        return this;
    }

    /**
     * 事件触发
     */
    emit(event, data = {}) {
        if (this.events[event]) {
            this.events[event].forEach(callback => {
                try {
                    callback.call(this, data);
                } catch (error) {
                    console.error(`Error in event handler for ${event}:`, error);
                }
            });
        }
        return this;
    }

    /**
     * 移除事件监听
     */
    off(event, callback) {
        if (this.events[event]) {
            if (callback) {
                const index = this.events[event].indexOf(callback);
                if (index > -1) {
                    this.events[event].splice(index, 1);
                }
            } else {
                delete this.events[event];
            }
        }
        return this;
    }

    /**
     * 查找子组件
     */
    findChild(predicate) {
        return this.children.find(predicate);
    }

    /**
     * 查找所有匹配的子组件
     */
    findChildren(predicate) {
        return this.children.filter(predicate);
    }

    /**
     * 显示组件
     */
    show() {
        if (this.element) {
            this.element.style.display = '';
        }
        this.emit('shown');
        return this;
    }

    /**
     * 隐藏组件
     */
    hide() {
        if (this.element) {
            this.element.style.display = 'none';
        }
        this.emit('hidden');
        return this;
    }

    /**
     * 切换显示/隐藏
     */
    toggle() {
        if (this.element) {
            this.element.style.display === 'none' ? this.show() : this.hide();
        }
        return this;
    }

    /**
     * 添加CSS类
     */
    addClass(className) {
        if (this.element) {
            this.element.classList.add(className);
        }
        return this;
    }

    /**
     * 移除CSS类
     */
    removeClass(className) {
        if (this.element) {
            this.element.classList.remove(className);
        }
        return this;
    }

    /**
     * 切换CSS类
     */
    toggleClass(className) {
        if (this.element) {
            this.element.classList.toggle(className);
        }
        return this;
    }

    /**
     * 检查是否包含CSS类
     */
    hasClass(className) {
        return this.element ? this.element.classList.contains(className) : false;
    }

    /**
     * 设置属性
     */
    setAttribute(name, value) {
        if (this.element) {
            this.element.setAttribute(name, value);
        }
        return this;
    }

    /**
     * 获取属性
     */
    getAttribute(name) {
        return this.element ? this.element.getAttribute(name) : null;
    }

    /**
     * 移除属性
     */
    removeAttribute(name) {
        if (this.element) {
            this.element.removeAttribute(name);
        }
        return this;
    }

    /**
     * 销毁组件
     */
    destroy() {
        this.unmount();
        this.state = {};
        this.props = {};
        this.children = [];
        this.emit('destroyed');
    }
}

// 导出组件
window.BaseComponent = BaseComponent;